
class TimeUtils {

  TimeUtils();

  static const dayTimeLen = 24 * 3600 * 1000;

  static getOneDayTimeLen(){
    return dayTimeLen;
  }

  /*
  获取一周的开始和结束时间
   */
  static getWeekTime(DateTime? dateTime){
    dateTime ??= DateTime.now();
    const dayLengthTime = dayTimeLen;
    int year = dateTime.year;
    int month = dateTime.month;
    int day = dateTime.day;
    int weekDay = dateTime.weekday;
    DateTime weekStart = DateTime(year, month, day - weekDay);
    DateTime weekEnd = DateTime(year, month, day + (6 - weekDay), 23, 59, 59, 999);
    return {
      'weekStartTime': weekStart.millisecondsSinceEpoch + dayLengthTime,
      'weekEndTime': weekEnd.millisecondsSinceEpoch + dayLengthTime
    };
  }

  static formatTime(DateTime? dateTime, String? formatStr) {
    dateTime ??= DateTime.now();
    formatStr ??= "yyyy-MM-dd HH:mm:ss.SSS";
    var o = {
      "M+": dateTime.month, //月份
      "d+": dateTime.day, //日
      "H+": dateTime.hour, //小时
      "m+": dateTime.minute, //分
      "s+": dateTime.second, //秒
      "q+": ((dateTime.month + 3) / 3).floor(), //季度
      "S+": dateTime.millisecond//毫秒
    };
    //处理年份
    var reYear = RegExp("(y+)");
    var resultYear = reYear.firstMatch(formatStr);
    if(resultYear != null){
      var yearformatPart = resultYear[0]; //匹配到的格式化字符
      if(yearformatPart != null){
        var yearVal = (dateTime.year.toString()).substring(4 - yearformatPart.length);
        formatStr = formatStr.replaceAll(RegExp(yearformatPart), yearVal);
      }
    }
    //周
    var week = {
      "1": "一",
      "2": "二",
      "3": "三",
      "4": "四",
      "5": "五",
      "6": "六",
      "7": "日",
    };
    // 处理周几
    var reWeek = RegExp("(E+)");
    var resultWeek = reWeek.firstMatch(formatStr);
    if(resultWeek != null) {
      var weelformatPart = resultWeek[0]; //匹配到的格式化字符
      if(weelformatPart != null){
        var weekVal = ((weelformatPart.length > 1) ? "周" : "") + week["${dateTime.weekday}"]!;
        formatStr = formatStr.replaceAll(weelformatPart, weekVal);
      }
    }
    // 处理其他
    for (var key in o.keys) {
      var re = RegExp("($key)");
      var res = re.firstMatch(formatStr!);
      if(res == null)
        continue;
      var val = o[key].toString(); //本次需要替换的数据
      var formatPart = res[0]; //匹配到的格式化字符
      if(formatPart == null)
        continue;
      var replaceVal = "";
      if('SSS' == formatPart){
        replaceVal = ("000$val").substring((val).length);
      } else {
        replaceVal = (formatPart.length == 1) ? (val) : (("00$val").substring(val.length));
      }
      formatStr = formatStr.replaceAll(formatPart, replaceVal);
    }
    return formatStr;
  }
}